package com.huluobo.lc.kotlinim1803a.contract.contract

import android.util.Log
import com.huluobo.lc.kotlinim1803a.data.ContactListItem
import com.huluobo.lc.kotlinim1803a.data.db.Contact
import com.huluobo.lc.kotlinim1803a.data.db.IMDatabase
import com.hyphenate.chat.EMClient
import com.hyphenate.exceptions.HyphenateException
import org.jetbrains.anko.doAsync

/**
 * @author Lc
 * @description:
 * @date :2020/9/15 16:16
 */
class ContactPresenter(val view: ContactContact.View) : ContactContact.Presenter {
    val contactListItems = mutableListOf<ContactListItem>()//可变的list

    override fun loadContacts() {
        doAsync {
            try {
                //再次加载数据,先清空集合
                contactListItems.clear()
                //清空数据库
                IMDatabase.instance.deleteAllContacts()
                val userNames = EMClient.getInstance().contactManager().allContactsFromServer
                userNames.sortBy { it[0] }
                //什么时候显示首字符
                //1.当index=0显示
                //2.username上一位的首字符如果和当前首字符不同的时候
                userNames.forEachIndexed { index, s ->
                    val showFirstLetter = index == 0 || s[0] != userNames[index - 1][0]
                    val contactListItem = ContactListItem(s, s[0].toUpperCase(), showFirstLetter)
                    contactListItems.add(contactListItem)

                    val contact = Contact(mutableMapOf("name" to s))
                    IMDatabase.instance.saveContact(contact)
                }
                runOnUIThread { view.onLoadContactSuccess() }
            } catch (e: HyphenateException) {
                runOnUIThread { view.onLoadContactFailed() }
            }
        }
    }
}